﻿#include "mainadapte.h"
#include <QtWidgets>
#include <QPaintEvent>
#include <QPainter>
#include<qtlog.h>
#include"videoitem.h"

MainAdapte::MainAdapte(QObject *parent) : QObject(parent)
{
//    qRegisterMetaType<QVariantMap>("QVariantMap");
//    qRegisterMetaType<QVariantMap>("QVariantMap&");
//    avformat_network_init();
//    av_register_all();
    qRegisterMetaType<QImage>("QImage");
    qRegisterMetaType<QTextCursor>("QTextCursor");

    if(!m_ffmpeg){
        m_ffmpeg = new FFmpegOpt(this);
        connect(m_ffmpeg,&FFmpegOpt::sig_play,this,&MainAdapte::s_play);
    }

    m_widget = new QWidget(nullptr);
    m_widget->installEventFilter(this);
    m_widget->resize(600,400);
    m_widget->show();
}


void MainAdapte::startExe()
{

    if(!m_engine)
        m_engine = new QQmlApplicationEngine(this);
    const QUrl url(QStringLiteral("qrc:/qml/main.qml"));

    qmlRegisterType<VideoItem>("VideoItem", 1, 0, "VideoItem");
    m_engine->rootContext()->setContextProperty("CPPObJ",this);
    m_engine->load(url);

    QTimer::singleShot(500,this,[=]{
        QVariantMap a;
        a["tst"] = 2222222;
        emit sig_callQmlFunc("1111111",a);});
}

QVariantMap MainAdapte::callCppFunc(QString funcStr, QVariantMap pData)
{
    if(funcStr == "stop"){
        m_ffmpeg->stopPlay();
    }else if(funcStr == "playVideo"){
        pData = m_ffmpeg->openVideo("./tst.mp4");
        pData["total"] = m_ffmpeg->getTotal();
    }else if(funcStr == "pauseVideo"){
        m_ffmpeg->pausePlay(!m_ffmpeg->isPlay());
    }else if(funcStr == "getTime"){
        pData["pos"] = m_ffmpeg->getPos();
        pData["total"] = m_ffmpeg->getTotal();
    }else if(funcStr == "seekToPos"){
        m_ffmpeg->seekPos( pData["pos"].toDouble() );
    }else if(funcStr == "openUrlVideo"){
        pData = m_ffmpeg->openVideo(pData["url"].toString());
//        m_ffmpeg->openUrlVideo(pData["url"].toString());
    }

    return pData;
}

bool MainAdapte::eventFilter(QObject *watched, QEvent *event)
{
    if(watched == m_widget){
        QEvent::Type _type = event->type();
        if(_type == QEvent::Paint){
            QPaintEvent *paintE = static_cast<QPaintEvent*>(event);
            QPainter p(m_widget);
            p.drawImage(paintE->rect(),m_img);
        }
    }
    return QObject::eventFilter(watched,event);
}

void MainAdapte::s_play( QImage img)
{
    m_img = img;
    m_widget->update();

    static VideoItem *videoItem = nullptr;
    if(!videoItem){
        QObject *pRoot = m_engine->rootObjects().first();
        videoItem = pRoot->findChild<VideoItem *>("videoItem");
    }
    videoItem->setImg(img);
}











